package cy.security.demo.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import cy.security.core.properties.SecurityProperties;
import cy.security.demo.dto.User;
import cy.security.demo.dto.UserQueryCondition;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ciyuan
 * @Date: 2019/5/3 18:24
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

//    @Autowired
//    private AppSignUpUtils appSignUpUtils;

    @Autowired
    private SecurityProperties securityProperties;


    @GetMapping("/me")
    public Object findMe(Authentication user,HttpServletRequest request) throws UnsupportedEncodingException {
        String hander = request.getHeader("Authorization");
        String token = StringUtils.substringAfter(hander, "bearer ");

        Claims claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigninkKey().getBytes("UTF-8"))
                .parseClaimsJws(token).getBody();

        String author = (String) claims.get("author");

        log.info("author:" + author);

        return user;
    }

    /**
     * 注册
     *
     * @return
     */
    @PostMapping("/registered")
    public Object registered(@RequestBody User user, HttpServletRequest request) {
        //不管是注册用户还是绑定用户，都会拿到用户的唯一标识
        //正常逻辑下这里应该是先保存用户的业务信息 获取用户的唯一id
        String userId = user.getUsername();

        //将用户的唯一id传递给spring social，由spring social将用户id与用户对应第三方授权的信息绑定保存到数据库的表中
        //web模式下实现
        //providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));

        //app模式下实现
//        appSignUpUtils.doPostSignUp(new ServletWebRequest(request), userId);

        return user;
    }

    @GetMapping("")
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition condition, @PageableDefault(size = 10,page = 1) Pageable pageable){
        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));
        System.out.println(ReflectionToStringBuilder.toString(pageable, ToStringStyle.MULTI_LINE_STYLE));
        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        return userList;
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User findOne(@PathVariable Integer id){
        System.out.println(id);
        User user = new User();
        user.setUsername("ciyuan");
        user.setPassword("123456");
        return user;
    }

    @PostMapping("")
    public User create(@Valid @RequestBody User user){
        User result = new User();
        result.setId(1);
        result.setUsername(user.getUsername());
        result.setPassword(user.getPassword());
        result.setBirthday(user.getBirthday());
        return result;
    }

    @PutMapping("")
    public User update(@Valid @RequestBody User user, BindingResult errors){
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> {
                        System.out.println(error.getDefaultMessage());
                    }
            );
        }
        return user;
    }

    @DeleteMapping("/{id}")
    public Integer del(@PathVariable Integer id){
//        throw new UserNotExistException(id);
        User user = new User();
        user.setUsername("shi ci yuan ya");
        return id;
    }
}
